package BtoB.util;



import java.net.URL;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import org.w3c.dom.Node;

public class WebServiceHelper {

	public static String getItemName(String url, String itemNumber) throws Exception	{
				
		SOAPMessage msg = MessageFactory.newInstance().createMessage();		
		MimeHeaders header = msg.getMimeHeaders();
		header.addHeader("SOAPAction", "");
		
		SOAPPart soap = msg.getSOAPPart();
		SOAPEnvelope envelope = soap.getEnvelope();
		SOAPBody body = envelope.getBody();
		
		body.addChildElement("getName").addChildElement("itemNumber").addTextNode(itemNumber);

		SOAPConnection sc = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage resp = sc.call(msg, new URL(url));
		sc.close();
		
		Node node = resp.getSOAPPart().getEnvelope().getBody().getElementsByTagName("getNameReturn").item(0);
		
		return node.getTextContent();
	}
	
	public static double quote(String url, String itemNumber) throws Exception	{
		
		SOAPMessage msg = MessageFactory.newInstance().createMessage();		
		MimeHeaders header = msg.getMimeHeaders();
		header.addHeader("SOAPAction", "");
		
		SOAPPart soap = msg.getSOAPPart();
		SOAPEnvelope envelope = soap.getEnvelope();
		SOAPBody body = envelope.getBody();
		
		body.addChildElement("quote").addChildElement("itemNumber").addTextNode(itemNumber);

		SOAPConnection sc = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage resp = sc.call(msg, new URL(url));
		sc.close();
		
		Node node = resp.getSOAPPart().getEnvelope().getBody().getElementsByTagName("quoteReturn").item(0);
		
		return Double.valueOf(node.getTextContent());
	}
	
	public static String order(String url, String itemNumber, int quantity, String key) throws Exception	{
		
		SOAPMessage msg = MessageFactory.newInstance().createMessage();		
		MimeHeaders header = msg.getMimeHeaders();
		header.addHeader("SOAPAction", "");
		
		SOAPPart soap = msg.getSOAPPart();
		SOAPEnvelope envelope = soap.getEnvelope();
		SOAPBody body = envelope.getBody();
		
		
		SOAPElement quote = body.addChildElement("order");
		quote.addChildElement("itemNumber").addTextNode(itemNumber);
		quote.addChildElement("quantity").addTextNode(""+ quantity);
		quote.addChildElement("key").addTextNode(key);

		SOAPConnection sc = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage resp = sc.call(msg, new URL(url));
		sc.close();
		
		Node node = resp.getSOAPPart().getEnvelope().getBody().getElementsByTagName("orderReturn").item(0);
		
		return node.getTextContent();
	}
}
